#include "simple_string.h"

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int MINI(int a, int b) { return a < b ? a : b; }
int str_split(char* buffer, int buffer_len, char split_char, str_section* out,
              int max_cout) {
  int out_index = 0;
  int begin = 0;
  while (1) {
    int index = str_index(buffer, buffer_len, split_char, begin);
    if (index == -1) {
      out[out_index].begin = begin;
      out[out_index].end = (int)strlen(buffer);
      out_index++;
      return out_index;
    }
    out[out_index].begin = begin;
    out[out_index].end = index;
    out_index++;
    begin = index + 1;
    if (out_index >= max_cout) {
      return out_index;
    }
  }
}
int section_str(str_section section, char* buffer, char* out_buffer,
                int buffer_len) {
  int count = MINI(section.end - section.begin, buffer_len - 1);
  strncpy(out_buffer, buffer + section.begin, count);
  out_buffer[count] = '\0';
  return count;
}
int str_index(char* buffer, int buffer_len, char pattern, int begin) {
  for (int i = begin; i < buffer_len; i++) {
    if (buffer[i] == pattern) {
      return i;
    }
  }
  return -1;  // not found
}
#ifdef __MACH__
int fw_value = 0;
int lr_value = 0;
int beep = 0;
int main() {
  char buffer[] =
      "cmd=2&uid=29cfad8d56fe41c1910c4c3fa4d20d04&topic=car&msg=1#2#3";
  str_section sections[10];
  str_section sections2[2];
  str_section sections3[3];
  int count = str_split(buffer, sizeof(buffer), '&', sections, 10);
  char out_buffer[100];
  char key_buffer[10];
  char value_buffer[100];
  char item_buffer[4];
  for (int i = 0; i < count; i++) {
    // printf("%d:%d\n", sections[i].begin, sections[i].end);
    section_str(sections[i], buffer, out_buffer, sizeof(out_buffer));
    // printf("%s\n", out_buffer);
    int count2 = str_split(out_buffer, sections[i].end - sections[i].begin, '=',
                           sections2, 2);
    if (count2 == 2) {
      section_str(sections2[0], out_buffer, key_buffer, sizeof(key_buffer));
      if (strcmp(key_buffer, "msg") == 0) {
        section_str(sections2[1], out_buffer, value_buffer,
                    sizeof(value_buffer));
        printf("%s\n", value_buffer);
        int count3 =
            str_split(value_buffer, sizeof(value_buffer), '#', sections3, 3);
        if (count3 == 3) {
          section_str(sections3[0], value_buffer, item_buffer,
                      sizeof(item_buffer));
          fw_value = atoi(item_buffer);
          printf("x1:%d\n", fw_value);
          section_str(sections3[1], value_buffer, item_buffer,
                      sizeof(item_buffer));
          lr_value = atoi(item_buffer);
          printf("x2:%d\n", lr_value);
          section_str(sections3[2], value_buffer, item_buffer,
                      sizeof(item_buffer));
          beep = atoi(item_buffer);
          printf("x3:%d\n", beep);
        }
      }
    }
  }
  return 0;
}

#endif
